package com.twoscreen;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.twoscreen.test.Test;

public class TestServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final Logger log = Logger.getLogger("com.twoscreen.TokenServlet.java");
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) {
		UserService userService = UserServiceFactory.getUserService();
		Boolean valid = false;
		try {
			valid = userService.isUserAdmin();
		} catch (Exception e) {
			log.warning(e.getMessage());
		}
		log.info("Valid: " + valid);
		
		int code = -1;
		if (request.getParameter("code") != null) {
			code = Integer.parseInt(request.getParameter("code"));
			log.info("code received: " + code);
		}
		
		if (valid) {
			JSONArray result = Test.runTest(code);
			response.setContentType("application/json, charset=UTF-8");
			try {
				response.getWriter().println(result);
				log.info("JSON sent");
			} catch (IOException e) {
				log.warning("JSON response error: " + e);
			}
			
		}
	}

}
